﻿using System.IO;
using System.Xml;
using System.Xml.Serialization;
using Fuse8.ContentManagementFramework.Domain;
using Fuse8.ContentManagementFramework.SystemFacade;
using Fuse8.DomainFramework.Common.Locator;

namespace Fuse8.ContentManagementFramework.Web.MvcPowered.Components.Editors
{
    /// <summary>
    /// Editor Settings 
    /// </summary>
    public class EditorSettingManager
    {
        private static EditorSetting settings;

        internal static void Clear()
        {
            settings = null;
        }

        /// <summary>
        /// Current editor settings
        /// </summary>
        public static EditorSetting Settings
        {
            get { return settings ?? (settings = SetUpSettings()); }
        }

        private static EditorSetting SetUpSettings()
        {
            EditorSetting result = null;
            var cmsContext = DependencyServiceLocator.Current.GetInstance<ICmsContext>();
            var path = cmsContext.MapPath("/admin/assets/xml/editorSettings.xml");
            if (File.Exists(path))
            {
                result = GetSettingsFromFile(path);
            }

            EditorSetting customSettings = null;
            if (!string.IsNullOrEmpty(CmsConfiguration.CustomEditorToolPath))
            {
                var pathToCustom = cmsContext.MapPath(CmsConfiguration.CustomEditorToolPath);
                if (File.Exists(pathToCustom))
                {
                    customSettings = GetSettingsFromFile(pathToCustom);                    
                }
            }

            if (result != null)
            {
                if (customSettings != null)
                {
                    result.MergeWith(customSettings);
                }
            }
            else if (customSettings != null)
            {
                result = customSettings;
            }

            return result;
        }

        private static EditorSetting GetSettingsFromFile(string path)
        {
            EditorSetting result;
            using (var stream = File.OpenRead(path))
            {
                var sr = new XmlSerializer(typeof (EditorSetting));
                result = sr.Deserialize(stream) as EditorSetting;
            }
            return result;
        }
    }
}